<?php
/**
 * @description : create our worker object.
 * @class-name : createObjectOfWorkerJob();
 * @author : stephen.mo <stephen.mo@achievo.com>
 * @date : 2010-03-29
 */

class createObjectOfWorkerJob {
    private $config;
    private $reader;
    private $writer;
    private $gmworker;
    
    const MAIN_NODE_NAME = 'servers';
    const SUB_NODE_NAME = 'hosts';
    const APC_KEY_NAME = 'gearman_client_hosts_ports';

    public static function getInstance() {
        static $instance = null ;
        return $instance ? ($instance) : ($instance = new createObjectOfWorkerJob()) ;
    }

    public function __construct() {
        $this->config = ConfigReaderFactory::getInstance()->getConfigReader(publicGearmandConfig::getSeverAddressList())->getConfig();
        $this->init(self::MAIN_NODE_NAME,self::SUB_NODE_NAME,self::APC_KEY_NAME);
    }
    
    //get apc name.
    private function getApcData($key) {
        return apc_fetch($key);
    }
    
    //set the error.
    private function error() {
        echo "Maybe your servers wasn't start gearmand! pls restart it again! ";
        die();
    }

    //init this gearmand.
    private function init($main_node,$subs_node,$apc_key) {
        $data = array() ;
        $data = $this->getApcData($apc_key);

        if (empty($data)) {
            $host_obj = $this->config->$main_node->$subs_node;
            //get the servers with loop.
            foreach($host_obj as $key=>$value) {
                $host_name = trim((string)$value->host);
                $host_port = trim((string)$value->port);
                if (empty($host_name)) continue;
                $hostlist = (!empty($host_port)) ? $host_name.":".$host_port : $host_name;
                $data[] = $hostlist;
            }
            //set value to apc.
            apc_store($apc_key,$data);
        }
        
        //add the servers from xml file or apc cache.
        $this->gmworker = new GearmanWorker();
        foreach($data as $key=>$value) {
            $result = $this->gmworker->addServer($value);
        }
    }

    //add the functions at current works.
    public function addFunctions($functions) {
        $methods = get_class_methods(publicGearmandConfig::GEARMAND_SUPPORT_METHODS_LIST) ;
        foreach ( array_intersect($functions, $methods) as $function_name ) {
            $this->gmworker->addFunction("{$function_name}",publicGearmandConfig::GEARMAND_SUPPORT_METHODS_LIST."::".$function_name);
        }
    }

    //work
    public function work() {
       return $this->gmworker->work();
    }

    //return code.
    public function returnCode() {
        return $this->gmworker->returnCode();
    }


}

?>
